# Dreams have to come true after all
from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser

from comment.models.User import User
from comment.models.bank_card import *


class Card(Resource):
    def post(self):
        rp = RequestParser()
        rp.add_argument('openingBank', required=True)
        rp.add_argument('holder', required=True)  # 开户银行
        rp.add_argument('bankBranch', required=True)  # 支行
        rp.add_argument('cityId', required=True)  # 城市id
        rp.add_argument('cardNum', required=True)  # 卡片号码

        args = rp.parse_args()

        openingBank = args.openingBank
        bankBranch = args.bankBranch
        cityId = args.cityId
        bankCardNum = args.cardNum

        uid = g.user_id
        cu = User.query.filte(User.id == uid).first()
        # 验证银行卡是否唯一
        cardInfo = BankCard.query.filter(BankCard.bankCardNum == bankCardNum).first()
        if cardInfo:  # 银行卡信息已存在(不允许一卡多人)
            return {'message': '银行卡已存在', 'code': 20011}
        # 把银行卡信息保存到数据库中
        card = BankCard(bankCardNum=bankCardNum, openingBank=openingBank, cityId=cityId, bankBranch=bankBranch,
                        userId=cu,
                        reservePhone=cu.phone)
        db.session.add(card)
        db.session.comit()
        return {'msg': "success"}
        pass

    def get(self):
        uid = g.user_id
        # 获取当前用户下的所用银行卡
        cardInfo = BankCard.query.filter(BankCard.userId == uid).all()
        if cardInfo:
            data_cardInfo = BankCard.query.filter(BankCard.userId == uid).all()
            return data_cardInfo
        else:
            return {}

    def delete(self):
        rp = RequestParser()
        rp.add_argument('cardNum', required=True)

        args = rp.parse_args()
        bankCardNum = args.cardNum

        cardInfo = BankCard.query.filter(BankCard.bankCardNum == bankCardNum)
        if cardInfo:
            cardInfo.delete()
            db.session.commit()
            return {'msg': 'success'}
        else:
            return {'code': 20008, 'message': 'no this card'}
